package com.googlecode.grt192.HH11.controller.autonomous;

import java.util.Random;

import com.googlecode.grt192.HH11.mechanism.HHMechanism;

/*
 * Autonomous Controller: Sends messages to HHMechanisms to actuate in autonomous mode.
 * 
 * @author gerberduffy
 */
public class HHAutonomousController extends Thread {

	private static final int MIN_CONTRACT_TIME_INDEX = 0; // index 0 of waitTime
	private static final int MAX_CONTRACT_TIME_INDEX = 1; // index 1 of waitTime
	private static final int MIN_RETRACT_TIME_INDEX = 2; // index 2 of waitTime
	private static final int MAX_RETRACT_TIME_INDEX = 3; // index 3 of waitTime

	// public static final int DEFAULT_WAIT_TIME = 3 * 1000; // Default time in
	// between
	// contraction and
	// retraction
	private HHMechanism mech;
	private static Random rand = new Random();
	private int[] waitTime;
	private boolean enabled = false; // Is by default not running

	/*
	 * @param controller The HHController that is being automated
	 * 
	 * @param waitTime The time in milliseconds between retractions and
	 * contractions
	 */
	public HHAutonomousController(HHMechanism mech, int[] waitTimes) {
		this.waitTime = waitTimes;
		this.mech = mech;
	}

	// // Set the wait time to something else.
	// public void setWaitTime(long millis) {
	// this.waitTime = millis;
	// }

	/*
	 * Enable the controller to start automatically actuating the mech
	 */
	public void enable() {
		enabled = true;
		if (!super.isAlive()) {
			start();
		}
	}

	/*
	 * Halts actuation
	 */
	public void disable() {
		this.enabled = false;
	}

	/*
	 * Alternates between retracting and extending controller, waiting in
	 * between for 'waitTime' milliseconds
	 */
	public void run() {
		enabled = true;
		int sleeptime;
		// While we're in auto mode
		while (true) {
			if (enabled) {
				mech.contract(); // Contraction
			}
			// Stay contracted for waitTime
			try {
				// get random number between our bounds
				// add +1 to call because it complains if the parameter is 0
				sleeptime = rand.nextInt(waitTime[MAX_CONTRACT_TIME_INDEX]
						- waitTime[MIN_CONTRACT_TIME_INDEX] + 1);
				sleeptime += waitTime[MIN_CONTRACT_TIME_INDEX];
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {
				System.out.println("Thread problem. Actuation halting");
				enabled = false;
				break;
			}

			// Retract
			if (enabled) {
				mech.retract();
			}

			// Stay retracted for waitTime
			try {
				// get random number between our bounds
				// add +1 to call because it complains if the parameter is 0
				sleeptime = rand.nextInt(waitTime[MAX_RETRACT_TIME_INDEX]
						- waitTime[MIN_RETRACT_TIME_INDEX] + 1);
				sleeptime += waitTime[MIN_RETRACT_TIME_INDEX];
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {
				System.out.println("Thread problem. Actuation halting");
				enabled = false;
				break;
			}
		}
	}
}
